package org.dcits.util;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JDBCUtil {
	private static String DB_Driver="com.mysql.jdbc.Driver";
	private static String DB_Url="jdbc:mysql://127.0.0.1:3306/dcits?characterEncoding=utf-8";
	private static String DB_Name="root";
	private static String DB_Password="123456";
	
	/**
	 * 
	 * @param sql
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static List<Map<String, Object>> query(String sql, Object... args) throws Exception {

		Class.forName(DB_Driver);
		List<Map<String, Object>> list = null;
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		connection = DriverManager.getConnection(DB_Url,
				DB_Name, DB_Password);
				ps = connection.prepareStatement(sql);
	    if(args != null){
		for (int i = 0; i < args.length; i++) {
			ps.setObject(i + 1, args[i]);
		}
	    }
		rs = ps.executeQuery();
		ResultSetMetaData metaData = rs.getMetaData();

		Map<String, Object> obj = null;

		list = new ArrayList<>();

		while (rs.next()) { 
			obj = new HashMap<String, Object>();
			for (int i = 0; i < metaData.getColumnCount(); i++) {
				obj.put(metaData.getColumnName(i + 1),  rs.getObject(i + 1));
			}
			list.add(obj);
		}

		return list;
	}

	/**
	 * 
	 * @param sql
	 * @throws Exception
	 */
	public static boolean update(String sql, Object... args) throws Exception {
		Class.forName(DB_Driver);
		Connection connection = DriverManager.getConnection(DB_Url,
				DB_Name, DB_Password);
		PreparedStatement ps = connection.prepareStatement(sql);

		for (int i = 0; i < args.length; i++) {
			ps.setObject(i + 1, args[i]);
		}
		int line = ps.executeUpdate();

		return line > 0;
	}

}
